<?php

namespace App\Logic;

use App\Model\Play;
use Exception;

class AdminPlayLogic
{
    /**
     * 比赛列表
     * @param $input
     * @return array
     */
    public static function listPlay($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = Play::query()->when(!empty($input['query']['matchId']), function ($query) use ($input) {
            $query->where('match_id', $input['query']['matchId']);
        })->when(!empty($input['query']['sportId']), function ($query) use ($input) {
            $query->where('sport_id', intval($input['query']['sportId']));
        })->when(!empty($input['query']['matchStatus']), function ($query) use ($input) {
            $status = intval($input['query']['matchStatus']);
            if ($status == 99) {
                $query->where('match_status', '>', 3);
            } else {
                $query->where('match_status', $status);
            }
        })->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            switch ($input['query']['searchType']) {
                case 'gameName':
                    $query->where('game_name', 'like', "%{$input['query']['keyword']}%");
                    break;
                case 'teamName':
                    $query->where('home_team_name', 'like', "%{$input['query']['keyword']}%")->orWhere('away_team_name', 'like', "%{$input['query']['keyword']}%");
                    break;
            }
        });
        $total = $query->count();
        if ($total) {
            $records = $query->orderBy('id', 'desc')->limit($pageSize)->offset($offset)->get()->toArray();
            array_walk($records, function (&$v) {
                $v['game_logo'] = img_url($v['game_logo'], 32);
                $v['home_team_logo'] = img_url($v['home_team_logo'], 32);
                $v['away_team_logo'] = img_url($v['away_team_logo'], 32);
            });
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 比赛详情
     * @throws Exception
     */
    public static function detailPlay($matchId): array
    {
        $play = Play::query()->where('match_id', $matchId)->first();
        if ($play) {
            throw new Exception('比赛不存在');
        }
        return $play->toArray();
    }
}